package com.yingda.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.hjq.toast.ToastUtils;
import com.yingda.ad.Constants;
import com.yingda.ad.R;
import com.yingda.bean.WorkBean;
import com.yingda.eventbus.EventBus;
import com.yingda.eventbus.Subscriber;
import com.yingda.eventbus.ThreadMode;
import com.yingda.fragment.ReadTabNewFragment;
import com.yingda.fragment.ReadTabTwoNewFragment;
import com.yingda.utils.ExcelUtils;
import com.yingda.utils.ExecutorsUtils;
import com.yingda.utils.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ExcelNewActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_create_excel;
    private TextView tv_read_excel2;
    public static final String TAG = "ExcelActivity";

    private TextView tv_read_excel1;
    private Map<String, WorkBean> workBeanMap2;
    private Map<String, WorkBean> workBeanMap1;
    private TextView tv_open_file;
    private ActivityResultLauncher<Intent> filePickerLauncher;
    private TextView tv_open_name1;
    private TextView tv_open_name2;

    private String clickItem = "";

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.excel_new_layout);

        tv_create_excel = findViewById(R.id.tv_create_excel);
        tv_read_excel2 = findViewById(R.id.tv_read_excel2);
        tv_read_excel1 = findViewById(R.id.tv_read_excel1);
        tv_open_file = findViewById(R.id.tv_open_file);
        tv_open_name1 = findViewById(R.id.tv_open_name1);
        tv_open_name2 = findViewById(R.id.tv_open_name2);


        tv_create_excel.setOnClickListener(this);

        tv_read_excel2.setOnClickListener(this);
        tv_read_excel1.setOnClickListener(this);
        tv_open_file.setOnClickListener(this);



        //   initPre();
        EventBus.getDefault().register(this);
        //创建表格
        FileUtils.createOrExistsFile(this);

        // 初始化文件选择器
        filePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                        Uri selectedFileUri = result.getData().getData();
                        handleSelectedFile(selectedFileUri);
                    }
                }
        );
    }

    private void createExtel() {
        ExecutorsUtils.getInstance().getSingleThread(() -> {
            //创建文件夹 再 sdcard 目录下创建 MyFile 文件夹
            boolean existsFile = FileUtils.createOrExistsFile(this);
            if (existsFile){
                //读取表格1
                readTable1();

            }

        });
    }

    private void readTable1() {
        String tab1Path = FileUtils.getTab1Path();
        if (tab1Path.isEmpty()){
            mHandler.post(() -> {
                ToastUtils.show("表格1.xls不存在");
            });
        }else {
            //开始读取表格1
            mHandler.post(() -> {
                ToastUtils.show("读取表格1.xls");
                showWaitingDlg();
            });
            try {
                InputStream inputStream = new FileInputStream(tab1Path);
                ExcelUtils.getInstance().readTab1Excel(inputStream,new File("表格1.xls"));
            } catch (FileNotFoundException e) {
                mHandler.post(() -> dismissWaitingDlg());
            }

        }
    }

    private void readTable2() {
        String tab2Path = FileUtils.getTab2Path();
        if (tab2Path.isEmpty()){
            mHandler.post(() -> {
                ToastUtils.show("表格2.xls不存在");
            });
        }else {
            //开始读取表格2
            mHandler.post(() -> {
                showWaitingDlg();
                ToastUtils.show("读取表格2.xls");

            });
            try {
                InputStream inputStream = new FileInputStream(tab2Path);
                ExcelUtils.getInstance().readTab2Excel(inputStream,new File("表格2.xlsx"));
            } catch (FileNotFoundException e) {
                mHandler.post(() -> {
                    ToastUtils.show("表格2.xlsx读取失败");
                    dismissWaitingDlg();
                });
            }

        }
    }


    public List<WorkBean> isMapContainedInAnother(Map<String, WorkBean> mapA, Map<String, WorkBean> mapB) {
        List<WorkBean> workBeans = new ArrayList<>();
        for (Map.Entry<String, WorkBean> entry : mapA.entrySet()) {
            String key = entry.getKey();
            WorkBean value = entry.getValue();

            // 检查 mapB 是否包含 mapA 的键值对
            if (mapB.containsKey(key)) {
                workBeans.add(value);
            }
        }
        return workBeans;  // 所有键值对都在 mapB 中
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_create_excel:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (!Environment.isExternalStorageManager()) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, 100);
                        return;
                    }
                }
                ExecutorsUtils.getInstance().getSingleThread(() -> createExtel());
                break;
            case R.id.tv_open_file:
                //打开本地文件
                openDownloadFolder();
                break;
            case R.id.tv_read_excel1:
                //选着文件
                clickItem = "1";
                openDownloadFolder();

                //先把客户的表格导入到手机
                //adb push /Users/duanlexian/Desktop/十位员工 号的的的文件夹.xls  /storage/emulated/0/Download
                //adb push /Users/duanlexian/Desktop/延长工期 队2024-08-03任工作务信息表.xls /storage/emulated/0/Download
//                File fileDir = Environment.getExternalStorageDirectory();
//                String path = fileDir.getAbsoluteFile() + File.separator + "Download";
//                File xlsFile = new File(path, "延长工期 队2024-08-03任工作务信息表.xls");
                //  readExcel(xlsFile);
                break;
            case R.id.tv_read_excel2:
                clickItem = "2";
                openDownloadFolder();
                //先把客户的表格导入到手机
                //adb push /Users/duanlexian/Desktop/十位员工 号的的的文件夹.xls  /storage/emulated/0/Download
                //adb push /Users/duanlexian/Desktop/延长工期 队2024-08-03任工作务信息表.xls /storage/emulated/0/Download
                File fileDir = Environment.getExternalStorageDirectory();
                String path = fileDir.getAbsoluteFile() + File.separator + "Download";
                File xlsFile = new File(path, "延长工期 队2024-08-03任工作务信息表.xls");
                //  readExcel(xlsFile);

                break;
        }
    }

    private void openDownloadFolder() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("*/*");  // 显示所有文件类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // 设置初始路径为 Download 目录
        Uri downloadUri = Uri.parse(DocumentsContract.buildRootUri("com.android.externalstorage.documents", "primary:Download").toString());
        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, downloadUri);
        filePickerLauncher.launch(intent);
    }

    private void handleSelectedFile(Uri fileUri) {
        if (fileUri != null) {
            Toast.makeText(this, "选中文件的 URI: " + fileUri.toString(), Toast.LENGTH_LONG).show();
            String fileUriString = fileUri.toString();
            if (clickItem.equals("1")){
                //点击了第一个
                if (!TextUtils.isEmpty(fileUriString)){
                    int index = fileUriString.lastIndexOf(".");
                   String start = fileUriString.substring(index -3);
                    tv_open_name1.setText(start);
                    if (start.equals("111.xls")){
                        showWaitingDlg();
                        ReadTabNewFragment readTabFragment = new ReadTabNewFragment();
                        Bundle bundle=new Bundle();
                        bundle.putString("fileUrl",fileUriString);
                        readTabFragment.setArguments(bundle);

                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.fl_content,readTabFragment )
                                .commitAllowingStateLoss();
                        //还原设置
                        clickItem = "";
                    }else {
                        Toast.makeText(this,"选的文件不合法",Toast.LENGTH_LONG).show();
                        //还原设置
                        clickItem = "";
                    }

                }

            }else if (clickItem.equals("2")){
                //点击了第二个
                if (!TextUtils.isEmpty(fileUriString)){
                    int index = fileUriString.lastIndexOf(".");
                    String start = fileUriString.substring(index -3);
                    tv_open_name2.setText(start);
                    if (start.equals("222.xlsx")){

                        showWaitingDlg();
                        ReadTabTwoNewFragment readTabTwoFragment = new ReadTabTwoNewFragment();

                        Bundle bundle=new Bundle();
                        bundle.putString("fileUrl",fileUriString);
                        readTabTwoFragment.setArguments(bundle);
                        getSupportFragmentManager().beginTransaction()
                                .replace(R.id.fl_content, readTabTwoFragment)
                                .commitAllowingStateLoss();
                        //还原设置
                        clickItem = "";

                    }else {
                        Toast.makeText(this,"选的文件不合法",Toast.LENGTH_LONG).show();
                        //还原设置
                        clickItem = "";
                    }

                }
            }

            // readFileContent(fileUri);
        } else {
            Toast.makeText(this, "未选中文件", Toast.LENGTH_SHORT).show();
            //还原设置
            clickItem = "";
        }


    }



    @RequiresApi(api = Build.VERSION_CODES.M)
    @Subscriber(tag = Constants.DIALOGCLOSE, mode = ThreadMode.MAIN)
    public void setGuestFreeMode(String count) {
        dismissWaitingDlg();
    }

    //表格 2 中的数据
    @Subscriber(tag = Constants.READTWO, mode = ThreadMode.MAIN)
    public void readxls2(Map<String, WorkBean> workBeanMap2) {
        this.workBeanMap2 = workBeanMap2;
        // 使用 for-each 循环遍历 entrySet
        for (Map.Entry<String, WorkBean> entry : workBeanMap2.entrySet()) {
            String key = entry.getKey();
            WorkBean value = entry.getValue();
            Log.i(TAG, "readxls2: key=" + key + "name=" + value.getName());
        }
        //开始合并表格
         List<WorkBean> workBeans = isMapContainedInAnother(workBeanMap1, workBeanMap2);
         ExcelUtils.getInstance().createExcel(workBeans, ExcelNewActivity.this);
    }

    @Subscriber(tag = Constants.READONE, mode = ThreadMode.MAIN)
    public void readxls1(Map<String, WorkBean> workBeanMap1) {
        this.workBeanMap1 = workBeanMap1;
        if (workBeanMap1== null || workBeanMap1.size() == 0){
            ToastUtils.show("读取表格1 失败");
        }else {
            //开始读取表格2
            ExecutorsUtils.getInstance().getSingleThread(() -> {
//            List<WorkBean> workBeans = isMapContainedInAnother(workBeanMap1, workBeanMap2);
//            ExcelUtils.getInstance().createExcel(workBeans, ExcelNewActivity.this);
                //创建文件夹 再 sdcard 目录下创建 MyFile 文件夹
                boolean existsFile = FileUtils.createOrExistsFile(this);
                if (existsFile){
                    //读取表格2
                    readTable2();

                }

            });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ExecutorsUtils.getInstance().closeThread();
        EventBus.getDefault().unregister(this);
        dismissWaitingDlg();

    }
}
